<template>
  <div class="chatCotent">
    <div class="message-box" ref="msgBox">
      <div v-for="(item, index) in list" :key="index" class="msg-list">
        <div class="msg-me" v-if="item.type == 'me'">
          <div class="msg-t">
            <span>{{ item.time }}</span>
            <div class="msg-txt" v-html="item.text" @click="prviateImg(item.text)"></div>
          </div>
          <el-avatar size="40" :src="userAvator" />
        </div>
        <div class="msg-you" v-if="item.type == 'you'">
          <el-avatar size="40" :src="chatMap.avatar" />
          <div class="msg-ts">
            <span>{{ item.time }}</span>
            <div class="msg-txt" v-html="item.content" @click="prviateImg(item.content)"></div>
          </div>
        </div>
      </div>
    </div>
    <div class="message-send">
      <div class="msg-button">
        <div class="icon-list">
          <!-- 表情 -->
          <el-popover placement="top-end" trigger="click" width="450">
            <template #reference>
              <svg
                t="1711676094089"
                class="icon"
                viewBox="0 0 1025 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="1538"
                width="22"
                height="22"
              >
                <path
                  d="M512.016 1024C229.232 1024 0.016 794.784 0.016 512 0.016 229.216 229.232 0 512.016 0 794.784 0 1024 229.216 1024 512 1024 794.784 794.784 1024 512.016 1024ZM512.016 64C264.976 64 64.016 264.96 64.016 512 64.016 759.024 264.976 960 512.016 960 759.04 960 960 759.024 960 512 960 264.96 759.04 64 512.016 64ZM510.336 833.456C509.056 833.456 507.744 833.488 506.448 833.488 310.992 833.488 229.024 657.12 225.616 649.552 218.336 633.424 225.488 614.496 241.584 607.216 257.712 599.968 276.576 607.088 283.888 623.088 286.64 629.12 352.928 769.488 506.576 769.488 507.584 769.488 508.576 769.456 509.584 769.456 672.896 767.552 738.368 624.768 739.024 623.344 746.176 607.216 765.024 599.872 781.264 607.152 797.392 614.336 804.672 633.248 797.456 649.408 794.176 656.8 714.208 831.056 510.336 833.456ZM671.504 479.84C636.224 479.84 607.664 451.232 607.664 415.984 607.664 380.768 636.224 352.176 671.504 352.176 706.768 352.176 735.344 380.768 735.344 415.984 735.344 451.232 706.768 479.84 671.504 479.84ZM351.504 479.84C316.224 479.84 287.664 451.232 287.664 415.984 287.664 380.768 316.224 352.176 351.504 352.176 386.768 352.176 415.344 380.768 415.344 415.984 415.344 451.232 386.768 479.84 351.504 479.84Z"
                  p-id="1539"
                ></path>
              </svg>
            </template>
            <Emoji @select-emoji="selectEmoji" />
          </el-popover>
          <!-- 上传图片 -->
          <uploadImgButton @update:model-value="updateModelValue" :limit="1">
            <el-icon :size="22" title="上传图片"><Picture /></el-icon>
          </uploadImgButton>
          <!-- 常用语 -->
          <el-popover placement="top-end" trigger="click" width="450">
            <template #reference>
              <svg
                title="快捷消息"
                t="1712717446492"
                class="icon"
                viewBox="0 0 1025 1024"
                version="1.1"
                xmlns="http://www.w3.org/2000/svg"
                p-id="2548"
                width="22"
                height="22"
              >
                <path
                  d="M336.012549 687.947294c-25.118118-25.077961-53.087373-37.787608-83.164863-37.787608-87.521882 0-171.891451 109.929412-250.699294 326.656-4.698353 12.729725-1.525961 27.186196 8.151843 36.884078 4.196392 4.176314 9.256157 7.168 14.777725 8.794353L25.077961 1024l10.039216 0c4.075922 0 8.111686-0.702745 12.047059-2.128314 197.491451-71.800471 306.517333-148.399686 324.085961-227.649255C377.113098 767.658667 375.747765 727.68251 336.012549 687.947294zM302.662275 778.962824c-2.871216 12.810039-15.641098 39.755294-69.170196 76.559059-34.55498 23.732706-80.373961 47.686275-136.412863 71.358745 26.322824-62.323451 52.966902-111.87702 79.349961-147.576471 27.407059-37.044706 53.930667-57.845961 74.892549-58.869961l1.525961 0c10.942745 0 21.905569 5.621961 33.490824 17.167059C300.574118 751.836863 305.754353 765.008314 302.662275 778.962824z"
                  fill="#262535"
                  p-id="2549"
                ></path>
                <path
                  d="M968.001255 0.060235l0.160627 0.180706c-123.26149 2.248784-233.612549 24.515765-328.282353 66.319059-82.743216 36.542745-153.6 87.823059-210.582588 152.415373-9.236078 10.460863-18.271373 21.504-26.864941 32.868392-43.670588 3.875137-88.124235 21.564235-132.196392 52.645647-38.068706 26.784627-76.338196 63.849412-113.724235 110.170353-60.134902 74.49098-98.223686 148.560314-102.460235 156.912941-7.690039 15.460392-3.132235 34.032941 10.802196 44.112314 13.552941 9.878588 33.390431 8.432941 45.517804-3.573961 0.220863-0.240941 23.471686-22.989804 62.925804-45.296941 30.639686-17.327686 78.908235-38.630902 137.236078-43.690667 18.150902 39.956078 59.01051 84.188863 82.602667 107.760941 23.572078 23.592157 67.804863 64.451765 107.760941 82.602667-5.059765 58.347922-26.322824 106.596392-43.65051 137.216-22.467765 39.695059-45.056 62.704941-45.296941 62.945882-12.207686 12.227765-13.773804 31.342431-3.654275 45.417412 6.585725 9.135686 17.247373 14.637176 28.511373 14.637176 5.561725 0 10.88251-1.28502 15.922196-3.83498 13.452549-6.866824 84.188863-43.851294 156.651922-102.359843 46.320941-37.365961 83.365647-75.615373 110.190431-113.684078 31.021176-44.112314 48.710275-88.545882 52.585412-132.176314 11.264-8.473098 22.26698-17.528471 32.948706-26.864941 64.592314-57.062902 115.852549-127.879529 152.355137-210.582588C1001.652706 284.250353 1024 166.811608 1024 35.137255L1024 0 968.001255 0.060235zM320.77302 440.500706c-37.24549 3.031843-74.069333 11.545098-109.969569 25.439373 39.915922-53.087373 92.943059-110.310902 151.732706-138.842353C336.574745 378.096941 325.350902 419.07702 320.77302 440.500706zM558.983529 815.646118c13.834039-35.799843 22.347294-72.583529 25.379137-109.768784 21.403608-4.597961 62.323451-15.801725 113.302588-41.72298C669.093647 722.823529 611.97051 775.770353 558.983529 815.646118zM763.723294 537.700392l-0.040157-0.040157-5.059765 4.47749c-102.038588 90.031686-206.426353 110.371137-220.661961 110.411294-0.120471 0-9.577412-1.365333-33.069176-17.909961-18.893804-13.291922-40.919843-32.225882-62.022275-53.328314-21.162667-21.182745-40.096627-43.168627-53.328314-62.002196-16.022588-22.768941-17.829647-32.366431-17.909961-32.38651 0.040157-15.078902 20.439843-119.366275 110.411294-221.364706 106.255059-120.410353 269.05098-187.552627 471.160471-194.56C946.356706 270.376157 880.941176 431.405176 763.723294 537.700392z"
                  fill="#262535"
                  p-id="2550"
                ></path>
                <path
                  d="M694.472784 175.686275c-74.711843 0-135.489255 60.79749-135.489255 135.509333 0 74.731922 60.777412 135.529412 135.489255 135.529412s135.529412-60.777412 135.529412-135.529412C830.002196 236.463686 769.184627 175.686275 694.472784 175.686275zM694.472784 376.45051c-35.960471 0-65.214745-29.254275-65.214745-65.254902 0-35.980549 29.254275-65.254902 65.214745-65.254902s65.254902 29.274353 65.254902 65.254902C759.727686 347.196235 730.433255 376.45051 694.472784 376.45051z"
                  fill="#262535"
                  p-id="2551"
                ></path>
              </svg>
            </template>
            <CommonPhrases
              :commonPhrases="commonPhrases"
              @list-get="listGet"
              @setlect-common="setlectCommon"
            />
          </el-popover>
        </div>
        <div class="icon-btn">
          <el-button @click="transferCRMleads" :disabled="chatMap.transformed" link>
            <svg
              t="1711676252415"
              class="icon"
              viewBox="0 0 1024 1024"
              version="1.1"
              xmlns="http://www.w3.org/2000/svg"
              p-id="6764"
              width="22"
              height="22"
            >
              <path
                d="M24.898063 795.362696c-2.606361 0-5.243421-0.49835-7.770987-1.538029a20.466124 20.466124 0 0 1-12.413728-22.26919C24.506137 651.860375 72.638367 552.711214 147.772578 476.858642c37.32714-37.645388 81.971943-70.118987 132.702348-96.526427 41.561581-21.63474 87.465051-39.355333 136.436392-52.670594 93.995791-25.557072 168.166047-26.851555 182.079942-26.851554h0.146333l7.383154 0.052188c0.178055 0.001023 0.356111 0.005117 0.534166 0.011257l0.279362 0.004093c2.178619 0 4.244674-0.828878 5.820566-2.334161a8.483208 8.483208 0 0 0 2.602268-5.904477v-202.512297A20.466124 20.466124 0 0 1 649.854695 74.862012l365.65698 326.542124a20.465101 20.465101 0 0 1-0.00921 30.538527l-365.654934 326.127685a20.466124 20.466124 0 0 1-34.088376-15.273868V552.558741c-0.047072-4.487198-3.723811-8.129144-8.214079-8.129144-124.891452 0-235.245815 19.388583-328.049454 57.627488-73.947176 30.470989-143.231145 77.507258-195.090257 132.443452a479.364719 479.364719 0 0 0-42.792618 52.216245 20.470217 20.470217 0 0 1-16.714684 8.645914zM607.489818 503.497349c27.004027 0 49.051159 21.925359 49.200562 48.87515V697.120185l314.453808-280.458554L656.69038 135.844921v156.961868l-0.002047 0.252757c-0.161682 13.186324-5.723352 25.973558-15.255448 35.080983-9.550517 9.124821-22.229281 13.999852-35.438117 13.652951l-7.073093-0.050142c-11.571546 0.008186-261.714653 2.199085-422.074921 163.928536-51.268664 51.758828-88.912006 115.656113-112.420419 190.641945 54.511521-54.709019 124.82596-101.341083 199.474101-132.10269 97.774861-40.287565 213.374692-60.71378 343.589382-60.71378z"
                p-id="6765"
              ></path>
            </svg>
            转CRM客户
          </el-button>
        </div>
      </div>
      <div class="textarea-box">
        <div
          id="message-input"
          @paste="handlePaste"
          contenteditable="true"
          spellcheck="false"
          autofocus
          ref="messageInputDom"
          @input="setInput"
        ></div>
        <span class="send-placholder" v-if="anyContent">请输入内容...</span>
        <div class="send-button">
          <el-button :type="anyContent ? 'info' : 'primary'" :disabled="anyContent" @click="sendMsg"
            >发送</el-button
          >
        </div>
      </div>
    </div>
  </div>
  <el-image-viewer
    v-if="dialogVisible"
    @close="dialogVisible = false"
    hide-on-click-modal
    :url-list="htmlStringUrl"
  ></el-image-viewer>
  <CustomerForm ref="customerFormRef" @success="getList" />
</template>

<script lang="ts" setup>
import { Picture } from '@element-plus/icons-vue'
import Emoji from '../components/emoji.vue'
import CommonPhrases from '../components/CommonPhrases.vue'
import { getNowFormatDate } from '@/utils/public'
import { getCommonphrase } from '@/api/service/workbench/index'
import CustomerForm from '../components/CustomerForm.vue'

/*自定义输入框dom 绑定ref*/
const messageInputDom = ref(null)
const msgBox = ref(null)
const commonPhrases = ref([])
const anyContent = ref(true)
const userAvator = ref(
  ''
)
const customerFormRef = ref(null)
const dialogVisible = ref(false)
const htmlStringUrl = ref([])
const list = ref([])
const props = defineProps({
  chatMap: Object,
  messageList: Object
})
watchEffect(() => {
  list.value = props.messageList[props.chatMap.sessionId]
    ? props.messageList[props.chatMap.sessionId]
    : []
})
onMounted(() => {
  listGet()
  keydownSend()
})
// 回车发送消息
const keydownSend = () => {
  document.getElementById('message-input').addEventListener('keydown', function (event) {
    if (event.key === 'Enter') {
      event.preventDefault()
      if (event.shiftKey) {
        // 在Firefox中，需要手动插入换行符
        document.execCommand('insertLineBreak')
      } else {
        sendMsg()
      }
    }
  })
}

const listGet = async () => {
  commonPhrases.value = await getCommonphrase()
}
const emit = defineEmits(['customerSendMessage', 'crmUpdate'])

const updateModelValue = (val) => {
  const str = `<img src="${val}" style="max-width:250px;max-height:250px;vertical-align:middle;">`
  messageInputDom.value.innerHTML += str
  anyContent.value = false
}
/*选择常用语*/
const setlectCommon = (values) => {
  if (Object.keys(props.chatMap).length == 0) {
    return
  }
  let newMessage = {
    type: 'me',
    text: '',
    avatar: userAvator.value,
    time: getNowFormatDate(),
    fromUserKey: props.chatMap.sessionId
  }
  newMessage.text = values
  emit('customerSendMessage', newMessage, props.chatMap.loginUserId)
  scrollDom()
}
/*选择表情*/
const selectEmoji = (item) => {
  let emojiImg = `<img src="${item.Icon}"  style="vertical-align: middle;">`
  messageInputDom.value.innerHTML += emojiImg
  anyContent.value = false
}

const prviateImg = (htmlString) => {
  htmlStringUrl.value = extractImageLinks(htmlString)
  if (htmlStringUrl.value.length) dialogVisible.value = true
}
const extractImageLinks = (inputString) => {
  const imgSrcRegex = /<img.*?src=["'](.*?)["']/g
  const srcArray = []
  let match

  while ((match = imgSrcRegex.exec(inputString)) !== null) {
    srcArray.push(match[1])
  }
  return srcArray
}
/*发送消息*/
const sendMsg = () => {
  if (Object.keys(props.chatMap).length == 0) {
    return
  }
  let newMessage = {
    type: 'me',
    text: '',
    avatar: userAvator.value,
    time: getNowFormatDate(),
    fromUserKey: props.chatMap.sessionId
  }
  newMessage.text = messageInputDom.value.innerHTML
  emit('customerSendMessage', newMessage, props.chatMap.loginUserId)

  messageInputDom.value.innerHTML = ''
  anyContent.value = true
  scrollDom()
}
//滚动的底部
const scrollDom = () => {
  messageInputDom.value.focus()
  nextTick(() => {
    scrollToBottom()
  })
}
/*计算文本是否有内容*/
const setInput = () => {
  if (messageInputDom.value.innerHTML == '') {
    anyContent.value = true
  } else {
    anyContent.value = false
  }
}

/*复制的带样式的文本变为纯文本了*/
const handlePaste = (e) => {
  e.preventDefault()
  let text
  let clp = (e.originalEvent || e).clipboardData
  if (clp === undefined || clp === null) {
    text = window.clipboardData.getData('text') || ''
    if (text !== '') {
      if (window.getSelection) {
        var newNode = document.createElement('span')
        newNode.innerHTML = text
        window.getSelection().getRangeAt(0).insertNode(newNode)
      } else {
        document.selection.createRange().pasteHTML(text)
      }
    }
  } else {
    text = clp.getData('text/plain') || ''
    if (text !== '') {
      document.execCommand('insertText', false, text)
    }
  }
}
/*转crm成功之后*/
const getList = () => {
  emit('crmUpdate', props.chatMap.sessionId)
}
/*转线索*/
const transferCRMleads = () => {
  if (Object.keys(props.chatMap).length == 0) {
    return
  }
  customerFormRef.value.openByEnt(props.chatMap)
}
onMounted(() => {
  scrollToBottom()
})
defineExpose({ scrollDom })
/*滚动到底部*/
const scrollToBottom = () => {
  const chatLog = msgBox.value
  if (chatLog) {
    chatLog.scrollTop = chatLog.scrollHeight
  }
}
</script>

<style lang="scss" scoped>
.msg-t {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: flex-end;
  span {
    font-size: 14px;
    color: #909399;
    padding-right: 10px;
  }
}
.msg-ts {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: flex-start;
  span {
    font-size: 14px;
    color: #909399;
    padding-left: 10px;
  }
}
.chatCotent {
  height: 100%;
  flex: 2;
  border-left: 1px solid #ececec;
  border-right: 1px solid #ececec;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  .message-box {
    padding-bottom: 10px;
    height: 60%;
    border-bottom: 1px solid #ececec;
    overflow-y: auto;
    .msg-list {
      .msg-time {
        text-align: center;
        color: #999;
        font-size: 14px;
        margin: 18px 0;
      }
      .msg-me {
        display: flex;
        justify-content: flex-end;
        align-items: flex-start;
        padding-right: 20px;
        margin-top: 10px;
        .el-image {
          width: 40px;
          height: 40px;
        }
        .msg-txt {
          max-width: 320px;
          padding: 9px;
          border-radius: 4px;
          background-color: rgb(180, 224, 255);
          color: #000;
          font-size: 14px;
          margin-right: 10px;
          line-height: 1.5;
          letter-spacing: 2px;
          word-wrap: break-word;
        }
        .msg-img {
          margin-right: 10px;
          img {
            max-width: 320px;
            max-height: 320px;
          }
        }
        .msg-all {
          max-width: 320px;
          padding: 9px;
          font-size: 14px;
          margin-right: 10px;
          border-radius: 4px;
          background-color: rgb(180, 224, 255);
          img {
            max-width: 320px;
            max-height: 320px;
          }
        }
      }
      .msg-you {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        padding-left: 20px;
        margin-top: 10px;
        .el-image {
          width: 40px;
          height: 40px;
        }
        .msg-txt {
          max-width: 320px;
          padding: 9px;
          border-radius: 4px;
          background-color: rgb(164, 234, 192);
          color: #000;
          font-size: 14px;
          line-height: 1.5;
          margin-left: 10px;
          letter-spacing: 2px;
          word-wrap: break-word;
        }
        .msg-img {
          margin-left: 10px;
          .el-image {
            max-width: 320px;
            max-height: 320px;
          }
        }
        .msg-all {
          max-width: 320px;
          padding: 9px;
          font-size: 14px;
          margin-left: 10px;
          border-radius: 4px;
          background-color: rgb(164, 234, 192);
          img {
            max-width: 320px;
            max-height: 320px;
          }
        }
      }
    }
    &::-webkit-scrollbar {
      width: 2px;
    }
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
    }
    &::-webkit-scrollbar-thumb {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:horizontal:start {
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
    }
    &::-webkit-scrollbar-thumb:horizontal:end {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
  }
  .message-send {
    height: 40%;
    .msg-button {
      padding: 15px;
      display: flex;
      justify-content: space-between;
      .icon-list {
        display: flex;
        .el-icon {
          cursor: pointer;
          margin-right: 20px;
        }
        .icon {
          margin-right: 20px;
          cursor: pointer;
        }
      }
      .icon-btn {
        display: flex;
        cursor: pointer;
        align-items: center;
        .icon {
          margin-right: 5px;
          font-size: 15px;
          color: #333;
        }
      }
    }
    .textarea-box {
      height: calc(100% - 56px);
      position: relative;
      margin: 0 auto;
      #message-input {
        width: 100%;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        color: #515a6e;
        overflow-y: auto;
        box-sizing: border-box;
        resize: none;
        line-height: 1.5;
        padding: 10px 15px;
        &::-webkit-scrollbar {
          width: 2px;
        }
        &::-webkit-scrollbar-track {
          background: #f1f1f1;
        }
        &::-webkit-scrollbar-thumb {
          background: #d8d8d8;
        }
        &::-webkit-scrollbar-thumb:hover {
          background: #d8d8d8;
        }
        &::-webkit-scrollbar-thumb:horizontal:start {
          border-top-left-radius: 4px;
          border-bottom-left-radius: 4px;
        }
        &::-webkit-scrollbar-thumb:horizontal:end {
          border-top-right-radius: 4px;
          border-bottom-right-radius: 4px;
        }
        &::placeholder {
          font-size: 15px;
        }
      }
      .send-placholder {
        position: absolute;
        top: 10px;
        left: 15px;
        color: #909399;
      }
      .send-button {
        position: absolute;
        right: 20px;
        bottom: 20px;
      }
    }
  }
}
[contenteditable]:focus {
  outline: none;
}
</style>
